#include <iostream>
#include <sstream>
#include "CAsciiFileRead.h"
#include "Config.h"

using std::istringstream;

CAsciiFileRead::CAsciiFileRead()
{

    this->m_fileInPath = PATH_TXT;
    this->m_columns = COLUMNS_TXT;
    this->m_status = 0;
    this->Init();

}

CAsciiFileRead::CAsciiFileRead(string path, int col)
{

    this->m_fileInPath = path;
    this->m_columns = col;
    this->Init();

}

CAsciiFileRead::~CAsciiFileRead()
{
    if (this->m_fileIn.is_open())
    {
        this->m_fileIn.close();
    }
    
}

void CAsciiFileRead::Init()
{
    this->m_lineDoubleBuf.reserve(this->m_columns);
    this->m_allLinesDoubleBuf.reserve(LINES);
    this->Open();
}

void CAsciiFileRead::Open()
{
    this->m_fileIn.open(this->m_fileInPath, ios::in);
    if (!m_fileIn.is_open())
    {
        cerr << "File open error!" << endl;
        exit(0);
    }
}

void CAsciiFileRead::Load()
{
    this->m_lineDoubleBuf.clear();
    this->m_LineStringBuf.clear();

    vector<string> tempStrLine;
    std::getline(this->m_fileIn, m_strLine);
    tempStrLine = this->splitString();

    // solve multi-space split problem
    double temp = 0.0;
    for (auto it = tempStrLine.begin(); it != tempStrLine.end(); ++it)
    {
        if (*it != "")
        {
            stringTo(*it, temp);            // 自动类型推导
            // stringTo<double>(*it, temp); // 显示指定类型
            m_lineDoubleBuf.push_back(temp);
            m_LineStringBuf.push_back(*it);
        }
    }
}

void CAsciiFileRead::loadAll()
{
    while (true)
    {
        if (m_fileIn.eof())
        {
            break;
        }
        this->Load();
        m_allLinesDoubleBuf.push_back(m_lineDoubleBuf);
    }
}

void CAsciiFileRead::skipLines(int lines)
{
    for (size_t i = 0; i < lines; i++)
    {
        if (m_fileIn.eof())
        {
            cerr << "File ends" << endl;
            return;
        }
        std::getline(m_fileIn, m_strLine);
    }
}
// 
vector<string> CAsciiFileRead::splitString(const char delim)
{
    vector<string> tempStrLine;
    tempStrLine.clear();
    istringstream iss(this->m_strLine);
    string temp;

    while (std::getline(iss, temp, delim))
    {
        tempStrLine.push_back(temp);
    }
    return tempStrLine;
}

vector<double> CAsciiFileRead::getLineBuf()
{
    return m_lineDoubleBuf;
}

int CAsciiFileRead::getcolumns()
{
    return m_columns;
}